package app

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"time"
	"yxService/app/models"
	"yxService/app/pkg/setting"
)

type Claims struct {
	AuthUser *models.User
	jwt.StandardClaims
}

func GetJWTSecret() []byte {
	return []byte(setting.JWTSetting.Secret)
}

func GenerateToken(authUser *models.User) (string, error) {
	nowTime := time.Now()
	fmt.Println("JWTSetting is :")
	fmt.Println(setting.JWTSetting.Expire)
	expireTime := nowTime.Add(setting.JWTSetting.Expire * time.Second)
	fmt.Println("expireTime")
	fmt.Println(expireTime)
	claims := Claims{
		AuthUser: authUser,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(),
			Issuer:    setting.JWTSetting.Issuer,
		},
	}

	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	token, err := tokenClaims.SignedString(GetJWTSecret())
	return token, err
}

func ParseToken(token string) (*Claims, error) {
	tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(GetJWTSecret()), nil
	})
	if err != nil {
		return nil, err
	}
	if tokenClaims != nil {
		if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
			return claims, nil
		}
	}

	return nil, err
}
